package com.yidian.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yidian.entity.Result;
import com.yidian.pojo.seckill.SeckillStatus;
import com.yidian.server.seckill.SeckillOrderServcie;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author whb
 * @create 2021-10-22 13:56
 * @desciption 秒杀订单控制类
 */
@RestController
@RequestMapping(value = "/seckill/order")
public class SeckillOrderController {
    @Reference
    private SeckillOrderServcie seckillOrderServcie;

    /**
     * 用户下单
     * @param id 商品id
     * @param time 商品所在的秒杀时间区间
     * @return
     */
    @RequestMapping("/addOrder")
    public Result addOrder(Long id,String time){
        try {
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            if ("anonymousUser".equals(username)){
                return new Result(403,"未登录，请先登录！");
            }

            Boolean bo = seckillOrderServcie.addOrder(id, time, username);//调用订单Service下单
            //抢单成功
            if (bo){
                return new Result(0,"抢单成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(200,e.getMessage());//200代表已经秒杀过，排队等待中。或许进入支付页面，或许商品已经售罄，或者其它结果
        }

        return new Result(1,"抢单失败！");
    }

    /**
     * 查询秒杀状态信息
     * @return
     */
    @RequestMapping("/queryStatus")
    public Result querySeckillStatus(){
        String username = SecurityContextHolder.getContext().getAuthentication().getName();//获取登录用户名

        //如果用户账号为anonymousUser，则表明用户未登录
        if ("anonymousUser".equals(username)){
            return new Result(403, "请先登录！");
        }

        try {
            SeckillStatus seckillStatus = seckillOrderServcie.querySeckillStatus(username);//获取秒杀状态信息对象
            if (seckillStatus!=null){
                Result result = new Result(seckillStatus.getStatus(), "秒杀状态信息！");
                result.setOther(seckillStatus);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(500, e.getMessage());//500：服务出现异常，抢单失败
        }

        return new Result(404, "没有秒杀状态信息");
    }
}
